package com.sum.tea.xinlian.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ConvertUtils
import com.function.commfun
import com.sum.tea.contants.AppConfig
import com.tools.DjxlExcel
import com.uhf.api.cls.R2000_calibration
import com.uhf.api.cls.Reader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.math.BigDecimal
import kotlin.math.pow

class SubCarryWaveViewModel : ViewModel() {

    private val myapp = AppConfig.getInstance()

    // UI状态数据类
    data class UiState(
        val power1: String = "",
        val ads1: String = "",
        val refPower1: String = "",
        val ads0: String = "",
        val power2: String = "",
        val ads2: String = "",
        val refPower3: String = "",
        val ads3: String = "",
        val power3: String = "",
        val ads4: String = "",
        val tagCount: Int = 0,
        val temperature: Int = 0,
        val returnLossList: String = ""
    )

    // LiveData来持有UI状态
    private val _uiState = MutableLiveData(UiState())
    val uiState: LiveData<UiState> = _uiState

    // 事件流，用于发送一次性事件如Toast
    private val _uiEvent = MutableLiveData<UiEvent>()
    val uiEvent: MutableLiveData<UiEvent> = _uiEvent

    // 定义UI事件
    sealed class UiEvent {
        data class ShowToast(val message: String) : UiEvent()
        data class EnableButtonOn(val enabled: Boolean) : UiEvent()
        data class EnableButtonOff(val enabled: Boolean) : UiEvent()
        // 其他事件
    }

    // 定义内部变量
    private var ant: Int = 1
    private var power: Int = 3000
    private var fre: Int = 915250
    private var fa2: Double = 0.0
    private var fa1: Double = 0.0
    private var fa0: Double = 0.0
    private var ra2: Double = 0.0
    private var ra1: Double = 0.0
    private var ra0: Double = 0.0
    private var er: Reader.READER_ERR = Reader.READER_ERR.MT_OK_ERR
    private var tablefre: IntArray = IntArray(0)
    private var htbindex: Int = 0
    private val Lires: MutableList<String> = mutableListOf()

    // 实例化R2000_calibration相关对象
    private val r2000pcmd = R2000_calibration()
    private val r2000macp = R2000_calibration().MAC_DATA(0x0B00.toShort())
    private val r2000macfp = R2000_calibration().MAC_DATA(0x0B04.toShort())
    private val rcmdo2 = R2000_calibration.R2000cmd.OEMread
    private val rcmdo = R2000_calibration.R2000cmd.readMAC

    // 数据类
    data class R2000Tdata(
        var trd: Array<Reader.TAGINFO>? = null,
        var power1: Double = 0.0,
        var refpower1: Double = 0.0,
        var power2: Double = 0.0,
        var power3: Double = 0.0,
        var refpower3: Double = 0.0
    )

    // MsgObj数据类
    data class MsgObj(
        var soh: ByteArray = ByteArray(1),
        var dataLen: ByteArray = ByteArray(1),
        var opCode: ByteArray = ByteArray(1),
        var status: ByteArray = ByteArray(2),
        var crc: ByteArray = ByteArray(2),
        var data: ByteArray = ByteArray(250)
    ) {
        fun getCheckCrcData(): ByteArray {
            val crcb = ByteArray((dataLen[0].toInt() and 0xFF) + 4)
            var p = 0
            crcb[p++] = dataLen[0]
            crcb[p++] = opCode[0]
            crcb[p++] = status[0]
            crcb[p++] = status[1]
            for (i in 0 until (dataLen[0].toInt() and 0xFF)) {
                crcb[p++] = data[i]
            }
            return crcb
        }
    }

    // 按钮点击处理
    fun onCwSetClicked(antStr: String, powerStr: String, freStr: String) {
        viewModelScope.launch {
            try {
                ant = antStr.toInt()
                power = powerStr.toInt()
                fre = freStr.toInt()
                myapp.Rparams.opant = ant
                myapp.Rparams.rpow[0] = power.toShort().toInt()
                myapp.Rparams.frequency = fre // 假设有这个字段
                _uiEvent.postValue(UiEvent.ShowToast(AppConfig.Constr_ok))
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    fun onButtonOnClicked() {
        viewModelScope.launch {
            try {
                val cpst = myapp.Mreader.CustomParam_ST().apply {
                    ParamName = "0"
                    ParamVal = byteArrayOf(
                        0x01, // 开启
                        0x01, // 天线ID
                        ant.toByte(),
                        ((power and 0xFF00) shr 8).toByte(),
                        (power and 0x00FF).toByte(),
                        ((fre and 0xFF000000.toInt()) shr 24).toByte(),
                        ((fre and 0x00FF0000) shr 16).toByte(),
                        ((fre and 0x0000FF00) shr 8).toByte(),
                        (fre and 0x000000FF).toByte()
                    )
                }
                myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_CUSTOM, cpst)
                _uiEvent.postValue(UiEvent.EnableButtonOn(false))
                _uiEvent.postValue(UiEvent.EnableButtonOff(true))
                _uiEvent.postValue(UiEvent.ShowToast(AppConfig.Constr_ok))
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    fun onButtonOffClicked() {
        viewModelScope.launch {
            try {
                val cpst = myapp.Mreader.CustomParam_ST().apply {
                    ParamName = "0"
                    ParamVal = byteArrayOf(
                        0x01, // 关闭
                        0x00, // 天线ID
                        ant.toByte(),
                        ((power and 0xFF00) shr 8).toByte(),
                        (power and 0x00FF).toByte(),
                        ((fre and 0xFF000000.toInt()) shr 24).toByte(),
                        ((fre and 0x00FF0000) shr 16).toByte(),
                        ((fre and 0x0000FF00) shr 8).toByte(),
                        (fre and 0x000000FF).toByte()
                    )
                }
                myapp.Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_CUSTOM, cpst)
                _uiEvent.postValue(UiEvent.EnableButtonOn(true))
                _uiEvent.postValue(UiEvent.EnableButtonOff(false))
                _uiEvent.postValue(UiEvent.ShowToast(AppConfig.Constr_ok))
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    fun onGetAfPowClicked() {
        viewModelScope.launch {
            try {
                ReadA0A1A2()

                val r2000td = R2000Tdata()
                val ads = DoubleArray(5)

                Readreflect_diff(fre)
                r2000td.refpower1 = ReadFPower() * 0.1
                ads[0] = (r2000td.refpower1 - ra0) / ra1
                r2000td.power1 = ReadPower() * 0.1
                ads[1] = (r2000td.power1 - fa0) / fa1

                // 更新UI状态
                _uiState.value = _uiState.value?.copy(
                    power1 = String.format("%.1f", r2000td.power1),
                    ads1 = String.format("%.1f", ads[1]),
                    refPower1 = String.format("%.1f", r2000td.refpower1),
                    ads0 = String.format("%.1f", ads[0])
                )

                val tagcnt = IntArray(1)
                tagcnt[0] = 0
                val tagCount = myapp.Mreader.TagInventory_Raw(
                    myapp.Rparams.uants,
                    myapp.Rparams.uants.size,
                    myapp.Rparams.readtime.toShort(),
                    tagcnt
                )

                for (i in 0 until tagcnt[0]) {
                    val tfs = Reader().TAGINFO()
                    myapp.Mreader.GetNextTag(tfs)
                }

                _uiState.value = _uiState.value?.copy(tagCount = tagcnt[0])

                val temval = IntArray(1)
                er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_RF_TEMPERATURE, temval)
                if (er == Reader.READER_ERR.MT_OK_ERR) {
                    _uiState.value = _uiState.value?.copy(temperature = temval[0])
                }

                r2000td.power2 = ReadPower() * 0.1
                ads[2] = (r2000td.power2 - fa0) / fa1
                _uiState.value = _uiState.value?.copy(
                    power2 = String.format("%.1f", r2000td.power2),
                    ads2 = String.format("%.1f", ads[2])
                )

                Readreflect_diff(fre)
                r2000td.refpower3 = ReadFPower() * 0.1
                ads[3] = (r2000td.refpower3 - ra0) / ra1
                _uiState.value = _uiState.value?.copy(
                    refPower3 = String.format("%.1f", r2000td.refpower3),
                    ads3 = String.format("%.1f", ads[3])
                )

                r2000td.power3 = ReadPower() * 0.1
                ads[4] = (r2000td.power3 - fa0) / fa1
                _uiState.value = _uiState.value?.copy(
                    power3 = String.format("%.1f", r2000td.power3),
                    ads4 = String.format("%.1f", ads[4])
                )

                _uiEvent.postValue(UiEvent.ShowToast(AppConfig.Constr_ok))
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    fun onGetReturnLossClicked(isFixedFre: Boolean) {
        viewModelScope.launch {
            try {
                ant = myapp.Rparams.opant
                power = myapp.Rparams.rpow[0].toInt()

                frequency_Returnloss3(isFixedFre)

                // 更新UI的returnLossList
                val returnLossList = buildReturnLossList()
                _uiState.value = _uiState.value?.copy(returnLossList = returnLossList)

                // 生成Excel文件（假设DjxlExcel已转为Kotlin并可用）
                val excelList = generateExcelData()
                val dexel = DjxlExcel("驻波报表")
                dexel.CreatereturnlossExcelfile(excelList)

                _uiEvent.postValue(UiEvent.ShowToast(AppConfig.Constr_ok))
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    // 获取前向-反向差值
    private suspend fun Readreflect_diff(frequency: Int): Double {
        return withContext(Dispatchers.IO) {
            try {
                val rcf2 = arrayOfNulls<Reader.Region_Conf>(1)
                er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_FREQUENCY_REGION, rcf2)
                val rg = when (rcf2[0]) {
                    Reader.Region_Conf.RG_PRC -> R2000_calibration.Region.PRC
                    Reader.Region_Conf.RG_EU -> R2000_calibration.Region.EU
                    Reader.Region_Conf.RG_EU2 -> R2000_calibration.Region.EU2
                    Reader.Region_Conf.RG_EU3 -> R2000_calibration.Region.EU3
                    Reader.Region_Conf.RG_KR -> R2000_calibration.Region.KR
                    else -> R2000_calibration.Region.NA
                }

                val et = R2000_calibration().VSWRReturnloss_DATA(
                    power,
                    intArrayOf(frequency),
                    intArrayOf(ant),
                    rg
                )
                val senddata = r2000pcmd.GetSendCmd(
                    R2000_calibration.R2000cmd.ReturnLossTest, et.ToByteData()
                )
                val hMsg = MsgObj()
                val re = SendandRev(senddata, 5000, hMsg)
                if (re != 0) {
                    throw Exception("no resp")
                }
                if ((hMsg.status[0].toInt() + hMsg.status[1].toInt()) != 0) {
                    throw Exception(ConvertUtils.bytes2HexString(hMsg.status))
                }
                if (hMsg.opCode[0] == 0.toByte()) {
                    throw Exception(AppConfig.Constr_excep)
                }

                val data = hMsg.data.copyOfRange(12, hMsg.dataLen[0].toInt() + 12)
                val et2 = R2000_calibration().VSWRReturnloss_DATA(data)
                BigDecimal((et2.Lires()[0].toDouble()) / 10).toDouble()
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
                0.0
            }
        }
    }

    // 获取前向功率值，即发射功率值,单位0.1 dbm
    private suspend fun ReadPower(): Int {
        return withContext(Dispatchers.IO) {
            try {
                val senddata = r2000pcmd.GetSendCmd(rcmdo, r2000macp.ToByteData())
                val hMsg = MsgObj()
                val re = SendandRev(senddata, 1000, hMsg)
                if (re != 0) {
                    throw Exception("no resp")
                }
                if (hMsg.opCode[0] == 0.toByte()) {
                    throw Exception(AppConfig.Constr_excep)
                }

                val data = hMsg.data.copyOfRange(12, hMsg.dataLen[0].toInt() + 12)
                val r2000data = R2000_calibration().MAC_DATA(data)
                val adp = r2000data.GetAddr()
                adp[0].`val`
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
                0
            }
        }
    }

    // 获取反向功率值，即发射功率值,单位0.1 dbm
    private suspend fun ReadFPower(): Int {
        return withContext(Dispatchers.IO) {
            try {
                val senddata = r2000pcmd.GetSendCmd(rcmdo, r2000macfp.ToByteData())
                val hMsg = MsgObj()
                val re = SendandRev(senddata, 1000, hMsg)
                if (re != 0) {
                    throw Exception("no resp")
                }
                if (hMsg.opCode[0] == 0.toByte()) {
                    throw Exception(AppConfig.Constr_excep)
                }

                val data = hMsg.data.copyOfRange(12, hMsg.dataLen[0].toInt() + 12)
                val r2000data = R2000_calibration().MAC_DATA(data)
                val adp = r2000data.GetAddr()
                adp[0].`val`
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
                0
            }
        }
    }

    // 获取前向-反向功率的 A0，A1，A2值
    private suspend fun ReadA0A1A2() {
        withContext(Dispatchers.IO) {
            try {
                val oemaddr = shortArrayOf(
                    0x91.toShort(),
                    0x92.toShort(),
                    0x93.toShort(),
                    0x03C6.toShort(),
                    0x03C7.toShort(),
                    0x03C8.toShort()
                )

                val r2000oem = R2000_calibration().OEM_DATA(oemaddr[0])
                for (i in 1 until oemaddr.size) {
                    r2000oem.AddTo(oemaddr[i], 0)
                }
                val senddata = r2000pcmd.GetSendCmd(rcmdo2, r2000oem.ToByteData())
                val hMsg = MsgObj()
                val re = SendandRev(senddata, 1000, hMsg)
                if (re != 0 || hMsg.opCode[0] == 0.toByte()) {
                    throw Exception("no any data resp")
                }

                val data = hMsg.data.copyOfRange(12, hMsg.dataLen[0].toInt() + 12)
                val r2000data = R2000_calibration().OEM_DATA(data)

                val adp = r2000data.GetAddr()
                fa2 = HexstrToQ724(adp[0].`val`).toDouble()
                        fa1 = HexstrToQ724(adp[1].`val`).toDouble()
                        fa0 = HexstrToQ724(adp[2].`val`).toDouble()
                        ra2 = HexstrToQ724(adp[3].`val`).toDouble()
                        ra1 = HexstrToQ724(adp[4].`val`).toDouble()
                        ra0 = HexstrToQ724(adp[5].`val`).toDouble()
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    // 获取反向功率值的AD值
    private suspend fun ReadFAD(): Int {
        return withContext(Dispatchers.IO) {
            try {
                val et = R2000_calibration().ENGTest_DATA(
                    R2000_calibration.SubCmd.ReadAD.Value().toByte(),
                    1,
                    1
                )
                val senddata = r2000pcmd.GetSendCmd(R2000_calibration.R2000cmd.ENGTEST, et.ToByteData())
                val hMsg = MsgObj()
                val re = SendandRev(senddata, 1000, hMsg)
                if (re != 0) {
                    throw Exception("no resp")
                }

                val isLow = ((hMsg.data[12].toInt() and 0x80) shr 7) == 1
                val adc = (hMsg.data[16].toInt() and 0xFF shl 24) or
                        ((hMsg.data[17].toInt() and 0xFF) shl 16) or
                        ((hMsg.data[18].toInt() and 0xFF) shl 8) or
                        (hMsg.data[19].toInt() and 0xFF)
                adc
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                0
            }
        }
    }

    // 发送和接收数据
    private suspend fun SendandRev(data: ByteArray, timeout: Int, hMsg: MsgObj): Int {
        return withContext(Dispatchers.IO) {
            try {
                println("send: ${ConvertUtils.bytes2HexString(data)}")
                val re = myapp.Mreader.DataTransportSend(data, data.size, timeout)
                if (re != 0) return@withContext 0xFEFD

                println("revd:")
                val ret1 = myapp.Mreader.DataTransportRecv(hMsg.soh, 1, 1000)
                println(ConvertUtils.bytes2HexString(hMsg.soh))
                if (ret1 == -2 || ret1 == -3) return@withContext 0xFEFD
                if (ret1 == -1) return@withContext Reader.READER_ERR.MT_IO_ERR.value()
                if (ret1 == -4) {
                    if (FlushDummyData2Mod() != Reader.READER_ERR.MT_OK_ERR) {
                        return@withContext Reader.READER_ERR.MT_IO_ERR.value()
                    }
                    return@withContext if (TestModLive() == Reader.READER_ERR.MT_OK_ERR) 0xFEFD else 0xFEFE
                }

                if ((hMsg.soh[0].toInt() and 0xFF) != 0xFF) {
                    if (FlushDummyData2Mod() != Reader.READER_ERR.MT_OK_ERR) {
                        return@withContext Reader.READER_ERR.MT_IO_ERR.value()
                    } else {
                        return@withContext 0xFEFD
                    }
                }

                // 接收dataLen
                if (myapp.Mreader.DataTransportRecv(hMsg.dataLen, 1, 1000) == -1) {
                    return@withContext 0xFEFD
                }
                println(ConvertUtils.bytes2HexString(hMsg.dataLen))

                // 接收opCode
                if (myapp.Mreader.DataTransportRecv(hMsg.opCode, 1, 1000) == -1) {
                    return@withContext 0xFEFD
                }
                println(ConvertUtils.bytes2HexString(hMsg.opCode))

                // 接收status
                if (myapp.Mreader.DataTransportRecv(hMsg.status, 2, 1000) == -1) {
                    return@withContext 0xFEFD
                }
                println(ConvertUtils.bytes2HexString(hMsg.status))

                // 接收data
                if ((hMsg.dataLen[0].toInt() and 0xFF) > 0) {
                    if (myapp.Mreader.DataTransportRecv(hMsg.data, hMsg.dataLen[0].toInt(), 1000) == -1) {
                        return@withContext 0xFEFD
                    }
                    val fdata = hMsg.data.copyOf(hMsg.dataLen[0].toInt())
                    println(ConvertUtils.bytes2HexString(fdata))
                }

                // 接收crc
                if (myapp.Mreader.DataTransportRecv(hMsg.crc, 2, 1000) == -1) {
                    return@withContext 0xFEFD
                }
                println(ConvertUtils.bytes2HexString(hMsg.crc))

                val scrc = ((hMsg.crc[0].toInt() and 0xFF) shl 8) or (hMsg.crc[1].toInt() and 0xFF)
                if (R2000_calibration.calcCrc_short(hMsg.getCheckCrcData()).toInt() != scrc) {
                    if (FlushDummyData2Mod() != Reader.READER_ERR.MT_OK_ERR) {
                        return@withContext Reader.READER_ERR.MT_IO_ERR.value()
                    } else {
                        return@withContext 0xFEFD
                    }
                }

                // 检查错误状态
                if (er != Reader.READER_ERR.MT_OK_ERR) {
                    if (FlushDummyData2Mod() != Reader.READER_ERR.MT_OK_ERR) {
                        return@withContext Reader.READER_ERR.MT_IO_ERR.value()
                    }
                }

                0
            } catch (ex: Exception) {
                ex.printStackTrace()
                0xFEFD
            }
        }
    }

    // 刷新模块数据
    private suspend fun FlushDummyData2Mod(): Reader.READER_ERR {
        return withContext(Dispatchers.IO) {
            try {
                val zerobuf = ByteArray(255) { 0 }
                zerobuf[0] = 0xFF.toByte()
                zerobuf[1] = 250.toByte()
                zerobuf[2] = 0x00
                myapp.Mreader.DataTransportSend(zerobuf, 255, 2000)
                Reader.READER_ERR.MT_OK_ERR
            } catch (ex: Exception) {
                Reader.READER_ERR.MT_IO_ERR
            }
        }
    }

    // 检查模块通信状态
    private suspend fun TestModLive(): Reader.READER_ERR {
        return withContext(Dispatchers.IO) {
            try {
                val cmd = byteArrayOf(0xFF.toByte(), 0x00, 0x03, 0x1D, 0x0C)
                val resp = ByteArray(50)
                val resp2 = ByteArray(50)
                myapp.Mreader.DataTransportSend(cmd, cmd.size, 1000)
                if (myapp.Mreader.DataTransportRecv(resp, 5, 1000) == -1) {
                    return@withContext Reader.READER_ERR.MT_CMD_FAILED_ERR
                }
                if (myapp.Mreader.DataTransportRecv(resp2, (resp[1].toInt() and 0xFF) + 2, 1000) == -1) {
                    return@withContext Reader.READER_ERR.MT_CMD_FAILED_ERR
                }
                Reader.READER_ERR.MT_OK_ERR
            } catch (ex: Exception) {
                Reader.READER_ERR.MT_CMD_FAILED_ERR
            }
        }
    }

    // 切换载波状态
    private suspend fun CW_On() {
        withContext(Dispatchers.IO) {
            try {
                val senddata = r2000pcmd.GetSendCmd(R2000_calibration.R2000cmd.carrier, byteArrayOf(0x01))
                val hMsg = MsgObj()
                SendandRev(senddata, 1000, hMsg)
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
            }
        }
    }

    private suspend fun CW_Off() {
        withContext(Dispatchers.IO) {
            try {
                val senddata = r2000pcmd.GetSendCmd(R2000_calibration.R2000cmd.carrier, byteArrayOf(0x00))
                val hMsg = MsgObj()
                SendandRev(senddata, 1000, hMsg)
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
            }
        }
    }

    // 设置频率
    private suspend fun setpll(fre: Int) {
        withContext(Dispatchers.IO) {
            try {
                if (fre == 0) throw Exception("no frequency")
                if (fre < 840000 || fre > 960000) throw Exception("840000-960000")

                val bdata = byteArrayOf(
                    ((fre and 0xFF000000.toInt()) shr 24).toByte(),
                    ((fre and 0x00FF0000) shr 16).toByte(),
                    ((fre and 0x0000FF00) shr 8).toByte(),
                    (fre and 0x000000FF).toByte()
                )
                val lb = mutableListOf<Byte>()
                lb.addAll(listOf(0x00, 0x00, 0x00, 0x00))
                lb.addAll(bdata.toList())
                val by2 = lb.toByteArray()

                val senddata = r2000pcmd.GetSendCmd(R2000_calibration.R2000cmd.SetTestFre, by2)
                val hMsg = MsgObj()
                SendandRev(senddata, 1000, hMsg)
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
            }
        }
    }

    // 频率返回损耗测试
    private suspend fun frequency_Returnloss3(isFixFre: Boolean) {
        withContext(Dispatchers.IO) {
            try {
                val apvr = myapp.Mreader.AntPortsVSWR().apply {
                    andid = ant
                    power = myapp.Rparams.rpow[0].toShort()
                }

                val rcf2 = arrayOfNulls<Reader.Region_Conf>(1)
                er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_FREQUENCY_REGION, rcf2)
                if (er == Reader.READER_ERR.MT_OK_ERR) {
                    apvr.region = rcf2[0]!!
                }

                apvr.frecount = 0
                val hdst2 = myapp.Mreader.HoptableData_ST()
                er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE, hdst2)
                if (isFixFre) {
                    apvr.frecount = hdst2.lenhtb
                    for (i in 0 until apvr.frecount) {
                        apvr.vswrs[i].frequency = hdst2.htb[i]
                    }
                }

                er = myapp.Mreader.ParamGet(Reader.Mtr_Param.MTR_PARAM_RF_ANTPORTS_VSWR, apvr)

                htbindex = 0

                if (er == Reader.READER_ERR.MT_OK_ERR) {
                    tablefre = commfun.Sort(hdst2.htb, hdst2.lenhtb)
                } else {
                    viewModelScope.launch {
                        _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${er}"))
                    }
                    return@withContext
                }

                var msg = "频率\tRL(dB)\tVSWR\t天线\n"
                val ls = mutableListOf<Array<String>>()

                for (j in 0 until apvr.frecount) {
                    val ft1 = "0"
                    val ft2 = apvr.vswrs[j].vswr.toString()
                    msg += "${tablefre[j]}\t-$ft1\t$ft2\t$ant\n"
                    ls.add(arrayOf(tablefre[j].toString(), ft1, ft2, ant.toString()))
                }

                // 更新UI状态
                _uiState.value = _uiState.value?.copy(returnLossList = msg)

                // 生成Excel文件
                val dexel = DjxlExcel("驻波报表")
                dexel.CreatereturnlossExcelfile(ls)
            } catch (ex: Exception) {
                _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
            }
        }
    }

    // 辅助方法：HexstrToQ724
    private fun HexstrToQ724(valInt: Int): String {
        val value_q714 = valInt * 1.0 / (2.0.pow(24).toInt())
        val q714 = value_q714.toString()
        return if (value_q714 > 0) {
            if (q714.length >= 6) q714.substring(0, 6) else q714
        } else {
            if (q714.length >= 7) q714.substring(0, 7) else q714
        }
    }

    // 数据规则检查
    fun CheckDatarule(data: String?, numk: Int): Boolean {
        if (data.isNullOrEmpty()) return false
        return when (numk) {
            2 -> data.all { it == '0' || it == '1' }
            10 -> data.all { it.isDigit() }
            else -> data.all { it.isDigit() || it in 'A'..'F' }
        }.also {
            if (it) {
                if (data.startsWith(".") || data.endsWith(".")) return false
            }
        }
    }

    // 设置天线功率
    fun setantpow(ant: Int, pow: Int) {
        viewModelScope.launch {
            try {
                val et = R2000_calibration().ENGTest_DATA(
                    R2000_calibration.SubCmd.SetTestAntPow.Value().toByte(),
                    ant,
                    pow
                )
                val senddata = r2000pcmd.GetSendCmd(R2000_calibration.R2000cmd.ENGTEST, et.ToByteData())
                val hMsg = MsgObj()
                SendandRev(senddata, 1000, hMsg)
            } catch (ex: Exception) {
                viewModelScope.launch {
                    _uiEvent.postValue(UiEvent.ShowToast("${AppConfig.Constr_excep} ${ex.message}"))
                }
            }
        }
    }

    // 构建Return Loss列表字符串
    private fun buildReturnLossList(): String {
        val sb = StringBuilder("频率\tRL(dB)\tVSWR\t天线\n")
        for (j in tablefre.indices) {
            val ft1 = "0"
            val ft2 = myapp.Mreader.AntPortsVSWR().vswrs[j].vswr.toString()
            sb.append("${tablefre[j]}\t-$ft1\t$ft2\t$ant\n")
        }
        return sb.toString()
    }

    // 生成Excel数据
    private fun generateExcelData(): List<Array<String>> {
        val excelList = mutableListOf<Array<String>>()
        for (j in tablefre.indices) {
            val ft1 = "0"
            val ft2 = myapp.Mreader.AntPortsVSWR().vswrs[j].vswr.toString()
            excelList.add(arrayOf(tablefre[j].toString(), ft1, ft2, ant.toString()))
        }
        return excelList
    }
}
